package com.easytoolsoft.easyreport.engine.query;

import com.easytoolsoft.easyreport.engine.data.ReportDataSource;
import com.easytoolsoft.easyreport.engine.data.ReportParameter;
import org.apache.commons.lang3.StringUtils;

/**
 * @author tomdeng
 */
public class MySqlQueryer extends AbstractQueryer implements Queryer {

  public MySqlQueryer(final ReportDataSource dataSource, final ReportParameter parameter) {
    super(dataSource, parameter);
  }

  @Override
  protected String preprocessSqlText(String sqlText) {
    sqlText = StringUtils.stripEnd(sqlText.trim(), ";");

    String sqlTextRow = "SELECT\n"
        + "\tconcat(@rownum := @rownum + 1,'') AS rownum,\n"
        + "\tsqlstr.* \n"
        + "FROM\n"
        + "\t( SELECT @rownum := 0 ) r inner join \t(\n"
        + sqlText
        + "\t) sqlstr on 1=1";
    if (this.parameter.getPageRowNum() > 0) {
      // 拼接分页
      sqlTextRow +=
          " limit " + (this.parameter.getPageNum() - 1) * this.parameter.getPageRowNum() + ","
              + this.parameter.getPageRowNum();
    }
    return sqlTextRow;
  }


  /**
   * 统计数据量
   */
  @Override
  public String countSqlText(String sqlText) {
    StringBuffer stringBuffer = new StringBuffer();
    return stringBuffer.append("select count(1) as totalNum from (").append(sqlText)
        .append(") as t").toString();
  }
}
